# -*- coding: utf-8 -*-
import json
import time

from django.contrib.auth import login, authenticate
from django.contrib.auth.views import LogoutView as BaseLogoutView
from django.core.cache import cache
from django.shortcuts import render, redirect

from .forms import RegisterForm, LoginForm
from .models import Goods  # 确保导入你的模型


def index(request):
    start_time = time.time()

    if request.method == 'GET':
        # 尝试从Redis获取缓存数据
        goods_list_cache = cache.get('goods_list')
        if goods_list_cache is None:
            # 如果缓存中没有数据，则从数据库查询并存入缓存
            goods_list = Goods.objects.all()
            goods_list_json = json.dumps(
                [{'id': g.id, 'name': g.name, 'price': g.price, 'storage': g.storage} for g in goods_list])
            cache.set('goods_list', goods_list_json, timeout=60 * 60)  # 缓存 60 分钟
            print('not use cache:', end='')
        else:
            print('use cache:', end='')
            goods_list_json = goods_list_cache

        goods_list_data = json.loads(goods_list_json)
        end_time = time.time()
        print(f"response time {end_time - start_time}")
        return render(request, 'index.html',
                      {'goods_list': goods_list_data, 'time': f"使用缓存，数据响应时间: {end_time - start_time} s"})


def index2(request):
    start_time = time.time()
    if request.method == 'GET':
        goods_list_cache = cache.get('goods_list')
        goods_list = Goods.objects.all()
        goods_list_json = json.dumps(
            [{'id': g.id, 'name': g.name, 'price': g.price, 'storage': g.storage} for g in goods_list])
        print('not use cache:', end='')
        goods_list_data = json.loads(goods_list_json)
        end_time = time.time()
        print(f"response time {end_time - start_time}")
        return render(request, 'index.html',
                      {'goods_list': goods_list_data, 'time': f"不使用缓存，数据响应时间: {end_time - start_time} s"})


def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('/')  # 重定向到首页或其他页面
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form})


def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                now = int(time.time())
                cache.set(f'user_activity_{user.id}', now, timeout=3600)  # 1小时过期
                return redirect('/')  # 重定向到首页或其他页面
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})


class LogoutView(BaseLogoutView):
    def dispatch(self, request, *args, **kwargs):
        user_id = request.user.id
        response = super().dispatch(request, *args, **kwargs)
        if user_id:
            cache.delete(f'user_activity_{user_id}')
        return response
def chatIndex(request):
    return render(request,'chat.html' , {'sessionKey': request.session.session_key})